/*
 * @Author: alan_mf
 * @Date: 2023-03-07 21:05:23
 * @LastEditors: upp24 1246815351@qq.com
 * @LastEditTime: 2023-10-30 09:14:10
 * @FilePath: /pure-admin-thin-i18n/src/utils/auth.ts
 * @Description:
 *
 */
import Cookies from "js-cookie";
import { storageSession } from "@pureadmin/utils";
import { useUserStoreHook } from "@/store/modules/user";

export interface DataInfo<T> {
  /** token */
  token: string;
  /** admin_id */
  admin_id: T;
  /** admin_id */
  admin_name: string;
  /** token */
  accessToken: string;
  /** `accessToken`的过期时间（时间戳） */
  expires: T;
  /** 用于调用刷新accessToken的接口时所需的token */
  refreshToken: string;
  /** 用户名 */
  username?: string;
  /** 当前登陆用户的角色 */
  roles?: Array<string>;
  role_id: T;
  admin_nick: string;
  role_name: string;
  admin_pass: string;
  admin_status: number;
  admin_create: number;
  admin_update: number;
}

export const sessionKey = "user-info";
export const TokenKey = "authorized-token";

/** 获取`token` */
export function getToken(): DataInfo<number> {
  // 此处与`TokenKey`相同，此写法解决初始化时`Cookies`中不存在`TokenKey`报错
  return Cookies.get(TokenKey)
    ? JSON.parse(Cookies.get(TokenKey))
    : storageSession().getItem(sessionKey);
}

/**
 * @description 设置`token`以及一些必要信息并采用无感刷新`token`方案
 * 无感刷新：后端返回`accessToken`（访问接口使用的`token`）、`refreshToken`（用于调用刷新`accessToken`的接口时所需的`token`，`refreshToken`的过期时间（比如30天）应大于`accessToken`的过期时间（比如2小时））、`expires`（`accessToken`的过期时间）
 * 将`accessToken`、`expires`这两条信息放在key值为authorized-token的cookie里（过期自动销毁）
 * 将`username`、`roles`、`refreshToken`、`expires`这四条信息放在key值为`user-info`的sessionStorage里（浏览器关闭自动销毁）
 */
export function setToken(data: DataInfo<Date>) {
  let expires = 0;
  // const { token, refreshToken } = data;
  const { token } = data;
  console.log(data, token);
  expires = new Date("3000/10/30 00:00:00").getTime(); // 如果后端直接设置时间戳，将此处代码改为expires = data.expires，然后把上面的DataInfo<Date>改成DataInfo<number>即可
  const cookieString = JSON.stringify({ token, expires });
  console.log(cookieString);
  expires > 0
    ? Cookies.set(TokenKey, cookieString, {
        expires: (expires - Date.now()) / 86400000
      })
    : Cookies.set(TokenKey, cookieString);
}
//setSessionKey
export function setSession(data: DataInfo<Date>) {
  console.log(data);
  function setSessionKey(
    admin_name: string,
    roles: Array<string>,
    admin_id,
    role_id,
    role_name,
    // expires: string,
    admin_nick: string,
    admin_pass: string,
    admin_status: number,
    admin_create: number,
    admin_update: number
  ) {
    console.log(data.admin_name, data.admin_id);
    useUserStoreHook().SET_USERNAME(data.admin_name);
    useUserStoreHook().SET_ROLES(roles);
    storageSession().setItem(sessionKey, {
      // refreshToken,
      // expires,
      admin_name,
      roles,
      role_name,
      admin_id,
      admin_nick,
      admin_pass,
      role_id,
      admin_status,
      admin_create,
      admin_update
    });
  }
  if (data.admin_id) {
    const {
      roles,
      admin_name,
      admin_id,
      admin_nick,
      admin_pass,
      role_id,
      role_name,
      admin_status,
      admin_create,
      admin_update
    } = data;
    setSessionKey(
      admin_name,
      roles,
      admin_id,
      role_id,
      role_name,
      admin_nick,
      admin_pass,
      admin_status,
      admin_create,
      admin_update
    );
  } else {
    const admin_name =
      storageSession().getItem<DataInfo<number>>(sessionKey)?.admin_name ?? "";
    const admin_id =
      storageSession().getItem<DataInfo<number>>(sessionKey)?.admin_id ?? "";
    const roles =
      storageSession().getItem<DataInfo<number>>(sessionKey)?.roles ?? [];
    const role_id =
      storageSession().getItem<DataInfo<number>>(sessionKey)?.role_id ?? "";
    const admin_nick =
      storageSession().getItem<DataInfo<number>>(sessionKey)?.admin_nick ?? "";
    const admin_pass =
      storageSession().getItem<DataInfo<number>>(sessionKey)?.admin_pass ?? "";
    const admin_status =
      storageSession().getItem<DataInfo<number>>(sessionKey)?.admin_status ??
      "";
    const admin_create =
      storageSession().getItem<DataInfo<number>>(sessionKey)?.admin_create ??
      "";
    const admin_update =
      storageSession().getItem<DataInfo<number>>(sessionKey)?.admin_update ??
      "";
    const role_name =
      storageSession().getItem<DataInfo<number>>(sessionKey)?.role_name ?? "";
    setSessionKey(
      admin_name,
      roles,
      admin_id,
      role_id,
      admin_nick,
      admin_pass,
      role_name,
      admin_status,
      admin_create,
      admin_update
    );
  }
}
/**获取session*/
export function getSessionKey() {
  const adminInfo = storageSession().getItem<DataInfo<number>>(sessionKey);
  return adminInfo;
}

/** 删除`token`以及key值为`user-info`的session信息 */
export function removeToken() {
  Cookies.remove(TokenKey);
  sessionStorage.clear();
}

/** 格式化token（jwt格式） */
export const formatToken = (token: string): string => {
  token = getToken().token;
  // return "Bearer " + token;
  return token;
};
